
import { ReactElement, useContext, isValidElement, FC, useEffect, useRef } from 'react';
import { KeepAliteContext } from './KeepAliveProvider';

export default function KeepAlive({ Content }: { Content: ReactElement | FC }): JSX.Element | null {
  const { childrenReactNode: dom, collectReactNode } = useContext(KeepAliteContext)

  const ref = useRef<HTMLDivElement>({} as HTMLDivElement)

  dom ?? collectReactNode(isValidElement(Content) ? Content : <Content />)

  useEffect(() => {
    dom && ref.current?.appendChild(dom)
  }, [dom])

  return dom ? (<div ref={ref}></div>) : null
}